package com.example.mynote.ui.clock;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Person;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mynote.MainActivity;
import com.example.mynote.MyPlayer;
import com.example.mynote.R;
import com.example.mynote.ui.MyDataViewModel;
import com.example.mynote.ui.cloud.CloudFragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobConfig;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.NOTIFICATION_SERVICE;
import static com.example.mynote.R.raw.music;

public class ClockFragment extends Fragment {

    //TODO:一开始的ViewModel
//    private ClockViewModel clockViewModel;
    //TODO:自己的一些变量
    private ArrayList<ClockBean> DATA = new ArrayList<>(); //数据，放在ArrayList，需引入ArrayList支持
    private Toolbar toolbar;
    private FloatingActionButton fab;
    private RecyclerView recyclerView;
    private ClockAdapter adapter; //适配器
    private Integer editPosition;//当前编辑闹钟位置

//    private MediaPlayer player;
//    private boolean hasPrepared;//闹钟准备标志
    public MyPlayer myPlayer;

    NotificationManager manager;//通知管理

    private String TAG = "MainActivity";
    //ViewModel声明
    private MyDataViewModel myDataViewModel;
    MutableLiveData<Boolean> ifLogin;
    MutableLiveData<String> startDownload;
    MutableLiveData<String> startUpload;

    private IntentFilter intentFilter;
    private TimeChangeReceiver timeChangeReceiver;

    Comparator<ClockBean> comparator = new Comparator<ClockBean>() {
        @Override
        public int compare(ClockBean o1, ClockBean o2) {
            Integer t1 = o1.getTime().get(Calendar.HOUR_OF_DAY)*60 + o1.getTime().get(Calendar.MINUTE);
            Integer t2 = o2.getTime().get(Calendar.HOUR_OF_DAY)*60 + o1.getTime().get(Calendar.MINUTE);
            return t1.compareTo(t2);
        }
    } ;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
//        clockViewModel =
//                new ViewModelProvider(this).get(ClockViewModel.class);
        View root = inflater.inflate(R.layout.fragment_clock, container, false);
//        final TextView textView = root.findViewById(R.id.text_home);
//        clockViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
//            @Override
//            public void onChanged(@Nullable String s) {
//                textView.setText(s);
//            }
//        });
        //TODO://////////////////////////////////////////////////////////////////////////////////////////

        //生成数据库 ，只有第一次使用时会建立新数据库
        createDB();
//        useDB();

        getBmobData();

        //TODO:标题栏设置(新移植版本没有标题栏了)
//        toolbar = findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
        //添加按钮设置
        fab = root.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
                //启动另一个活动
                Intent intent = new Intent();
                //TODO: getApplicationContext() 改为 getContext()
                intent.setClass(getActivity().getApplicationContext(), EditAlarmClock.class);
                //复用EditAlarmClock活动，需要传入一个bubble告诉新活动是新增还是修改
                Bundle bundle=new Bundle();
                bundle.putString("type", "new");
                intent.putExtras(bundle);
                startActivityForResult(intent,1);
            }
        });
        //recyclerView及适配器
        recyclerView = root.findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); //给RecyclerView设置布局
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new ClockAdapter(DATA,getContext()); //给RecyclerView设置Adapter
        recyclerView.setAdapter(adapter);
        //广播接收器
        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);//每分钟变化
        intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);//设置了系统时区
        intentFilter.addAction(Intent.ACTION_TIME_CHANGED);//设置了系统时间
        timeChangeReceiver = new TimeChangeReceiver();
        //TODO: BroadcastReceiver在Fragment中的使用(重要)
        getActivity().getApplicationContext().registerReceiver(timeChangeReceiver, intentFilter);
//        registerReceiver(timeChangeReceiver, intentFilter);//注册

        //同步数据库
        refresh();

        //添加recyclerView项目监听器
        adapter.setOnClickListener(new ClockAdapter.OnClickListener(){
            @Override
            public void onClick(View itemView, int position) {
                // click...
//                Intent dialIntent =  new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));//跳转到拨号界面并传入号码
//                startActivity(dialIntent);
//                Toast.makeText(getApplicationContext(),"点击操作",Toast.LENGTH_SHORT).show();
                Log.d("列表项点击", "onClick"+"位置"+position);
            }

            @Override
            public void onLongClick(View itemView, int position) {
                // longClick...
//                showPopupWindow();
//                showDialog1(position);
//                Toast.makeText(getApplicationContext(),"长按操作",Toast.LENGTH_SHORT).show();
                showDialog1(position);
                Log.d("列表项点击", "onLongClick"+"位置"+position);
            }

            @Override
            public void onCheckedChange(View itemView, int position, boolean isChecked) {
                Log.d("列表项子控件点击", "onCheckedChange"+"位置"+position);
                //TODO: 设置闹钟开启部分不采用先写数据库然后刷新DATA和布局的方式，而是先该DATA再写数据库
                DATA.get(position).setSelected(isChecked);
                ifCheckedSetDatabase(position, isChecked);
            }

        });

        myDataViewModel = new ViewModelProvider(getActivity()).get(MyDataViewModel.class);
        ifLogin = (MutableLiveData<Boolean>) myDataViewModel.getIfLogin();
        startDownload = (MutableLiveData<String>) myDataViewModel.getStartDownload();
        startUpload = (MutableLiveData<String>) myDataViewModel.getStartUpload();
        liveDataObserve();

        //TODO://////////////////////////////////////////////////////////////////////////////////////////

        return root;
    }

    /**
     * 监听liveData
     */
    private void liveDataObserve(){
        ifLogin.observe(getActivity(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean b) {
                Log.d(TAG, "用户登陆状态改变");
            }
        });
        startDownload.observe(getActivity(), new Observer<String>() {
            @Override
            //TODO:没办法监听单个livedata吗？（后面会置为false）
            public void onChanged(String b) {
                if(startDownload.getValue().equals("start"))downloadClockFromCloud();
            }
        });
        startUpload.observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(String b) {
                if(startUpload.getValue().equals("start"))uploadClockFromCloud();
            }
        });
    }

    /**
     * Bmob数据库的clock表Bean类
     */
    public class clock extends BmobObject {  //TODO:为什么必须用public，否则报错？？？？
        private Number id;
        private Number hour;
        private Number minute;
        private Boolean selected;
        private String remark;

        public Boolean getSelected() {
            return selected;
        }

        public Number getHour() {
            return hour;
        }

        public Number getId() {
            return id;
        }

        public Number getMinute() {
            return minute;
        }

        public String getRemark() {
            return remark;
        }

        public void setHour(Number hour) {
            this.hour = hour;
        }

        public void setId(Number id) {
            this.id = id;
        }

        public void setMinute(Number minute) {
            this.minute = minute;
        }

        public void setRemark(String remark) {
            this.remark = remark;
        }

        public void setSelected(Boolean selected) {
            this.selected = selected;
        }
    }

    /**
     * 从Bmob数据库下载clock数据
     */
    private void downloadClockFromCloud() {
        Bmob.initialize(getContext(),"72fa9d56a52f30cc685d026622b10f91");
        BmobQuery<clock> query = new BmobQuery<clock>();
        //返回50条数据，如果不加上这条语句，默认返回10条数据
        query.setLimit(200);
        //执行查询方法
        query.findObjects(new FindListener<clock>() {
            @Override
            public void done(List<clock> list, BmobException e) {
                if(list.size()==0){
                    Log.d(TAG, "云端数据库没有clock数据");

                }else{
                    SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(getContext());
                    SQLiteDatabase db = helper.getWritableDatabase();
                    //删除本地数据库全部内容
                    if(db.isOpen()){
                        String sql = "delete from clock";
                        db.execSQL(sql);
                    }
                    else {
                        Log.d(TAG, "useDB: 打开数据库失败");
                    }

                    Log.d(TAG, "list大小: "+list.size());
                    for(clock clo: list){
                        Log.d(TAG, clo.getHour().toString()+clo.getRemark());
                        Number hour = clo.getHour();
                        Number minute = clo.getMinute();
                        String remark = clo.getRemark();
                        Boolean selected = clo.getSelected();
                        //TODO:重要问题：新建的本地clock表用的是自增id，而不是云端表的id，可能会造成后续便签绑定闹钟id的问题
                        addClock(hour.intValue(),minute.intValue(),selected,remark);//
                    }
                    db.close();
                    refresh();
                    myDataViewModel.setStartDownload("finish");
                }
            }
        });
    }

    /**
     * 上传clock数据到Bmob数据库
     */
    private void uploadClockFromCloud() {
        Bmob.initialize(getContext(),"72fa9d56a52f30cc685d026622b10f91");
        BmobQuery<clock> query = new BmobQuery<clock>();
        //返回50条数据，如果不加上这条语句，默认返回10条数据
//        query.setLimit(200);
        //执行查询方法
        for(ClockBean bean:DATA){
            query.addWhereNotEqualTo("id", bean.getId());
            query.findObjects(new FindListener<clock>() {
                @Override
                public void done(List<clock> list, BmobException e) {
                    if(list.size()==0){
//                        Number number = 42;//测试用
                        clock c = new clock();
                        c.setId(bean.getId());
                        c.setHour(bean.getTime().get(Calendar.HOUR_OF_DAY));
                        c.setMinute(bean.getTime().get(Calendar.MINUTE));
//                        c.setId(number);
//                        c.setHour(number);
//                        c.setMinute(number);
                        c.setRemark(bean.getRemark());
                        c.setSelected(bean.getSelected());
                        c.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                Log.d(TAG, "闹钟"+bean.getId()+"同步成功");
                            }
                        });
                    }
                }
            });
        }


        myDataViewModel.setStartUpload("finish");
    }

    /**
     * Bmob数据库操作测试
     */
    private void getBmobData() {
        Bmob.initialize(getContext(),"72fa9d56a52f30cc685d026622b10f91");
//        BmobConfig config = new BmobConfig.Builder(getActivity().getApplicationContext())
//                .setApplicationId("72fa9d56a52f30cc685d026622b10f91")//设置appkey
////                .setConnectTimeout(30)//请求超时时间（单位为秒）：默认15s
////                .setUploadBlockSize(1024*1024)//文件分片上传时每片的大小（单位字节），默认512*1024
////                .setFileExpiration(2500)//文件的过期时间(单位为秒)：默认1800s
//                .build();
//        Bmob.initialize(config);


//        //查询记录
//        BmobQuery<clock> bmobQuery = new BmobQuery<clock>();
//        bmobQuery.getObject("1", new QueryListener<clock>() {
//            @Override
//            public void done(clock clock, BmobException e) {
//                if(e==null){
//                    Log.d(TAG, "done: 查询成功");
//                }else{
//                    Log.d(TAG, "done: 查询失败"+ e.getMessage());
//                }
//            }
//        });

        //新增记录
        clock c = new clock();
        c.setHour(1);
        c.setMinute(2);
        c.setId(10);
        c.setSelected(true);
        c.setRemark("测试");
        c.save(new SaveListener<String>() {
            @Override
            public void done(String objectId,BmobException e) {
                if(e==null){
                    Log.d(TAG, "添加数据成功，返回objectId为："+objectId);
                }else{
                    Log.d(TAG, "done: 添加失败"+ e.getMessage());
                }
            }
        });
    }


    /**
     * 长按recyclerView项弹出对话框
     */
    public void showDialog1(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("闹钟信息");
        String content = "";
        content = "备注： " + DATA.get(position).getRemark() + "\n";
        builder.setMessage(content);
        builder.setIcon(R.drawable.ic_baseline_settings_24);
//        //点击对话框以外的区域是否让对话框消失
//        builder.setCancelable(true);
        //设置正面按钮
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("对话框测试","点击了确定");
                dialog.dismiss();
            }
        });
        //设置反面按钮
        builder.setNegativeButton("删除闹钟", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("对话框测试","点击了删除");
                //删除闹钟操作不需要进行二次确认
//                DATA.remove(position);
                Integer id = DATA.get(position).getId();
                deleteClock(id);
                Toast.makeText(getContext(), "闹钟已删除", Toast.LENGTH_SHORT).show();
//                Collections.sort(DATA,comparator);
//                adapter.notifyDataSetChanged();//适配器刷新列表
                refresh();
            }
        });
        //设置中立按钮
        builder.setNeutralButton("编辑", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("对话框测试","点击了编辑");
                //复用新增联系人活动，需要传入一个bubble告诉新活动是新增还是修改
                Intent intent = new Intent();
                intent.setClass(getContext(), EditAlarmClock.class);
                Bundle bundle=new Bundle();
                //编辑的话，除了操作类型，还需要在bubble写入当前编辑的闹钟信息内容
                bundle.putString("type", "edit");
                String hourText = DATA.get(position).getTime().get(Calendar.HOUR_OF_DAY)+"";
                String minuteText = DATA.get(position).getTime().get(Calendar.MINUTE)+"";
                String remarkText = DATA.get(position).getRemark();
                bundle.putString("hour_passed", hourText);
                bundle.putString("minute_passed", minuteText);
                bundle.putString("remark_passed", remarkText);
                intent.putExtras(bundle);
                startActivityForResult(intent,1);
                editPosition = position; //编辑位置设为position，onActivityResult函数利用此变量修改闹钟数组对应元素

                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 销毁活动时注销监听器，此时监听和活动生命周期绑定
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().getApplicationContext().unregisterReceiver(timeChangeReceiver);
    }

    /**
     * 生成数据库
     */
    public void createDB(){
        SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(getContext());
        SQLiteDatabase db = helper.getReadableDatabase();
    }

//    /**
//     * 数据库操作
//     */
//    public void useDB()
//    {
//        SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(getContext());
//        SQLiteDatabase db = helper.getWritableDatabase();
//        if(db.isOpen()){
////            String sql = "create table clock(_id integer primary key autoincrement, hour integer , minute integer ,  selected integer);";
//            for (Integer i = 0; i<10;i++)
//            {
//                String sql = "insert into clock(hour,minute,selected,remark) values(7,8,1,null)";
//                db.execSQL(sql);
//            }
//
//            Cursor cursor = db.rawQuery("select * from clock", null);
//            while (cursor.moveToNext()){
//                int _id = cursor.getInt(cursor.getColumnIndex("_id"));
//                int hour = cursor.getInt(cursor.getColumnIndex("hour"));
//                Log.d(TAG, "useDB: "+_id+" "+hour);
//            }
//        }
//        else {
//            Log.d(TAG, "useDB: 打开数据库失败");
//        }
//
//        db.close();
//    }

    /**
     * 刷新数据
     */
    public void refresh()
    {
        SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(getContext());
        SQLiteDatabase db = helper.getWritableDatabase();
        if(db.isOpen()){
//            String sql = "create table clock(_id integer primary key autoincrement, hour integer , minute integer ,  selected integer);";
//            for (Integer i = 0; i<10;i++)
//            {
//                String sql = "insert into clock(hour,minute,selected,remark) values(7,8,1,null)";
//                db.execSQL(sql);
//            }
            DATA.clear();//清空DATA
            Cursor cursor = db.rawQuery("select * from clock", null);
            while (cursor.moveToNext()){
                int _id = cursor.getInt(cursor.getColumnIndex("_id"));
                int hour = cursor.getInt(cursor.getColumnIndex("hour"));
                int minute = cursor.getInt(cursor.getColumnIndex("minute"));
                int selected_int = cursor.getInt(cursor.getColumnIndex("selected"));
                String remark = cursor.getString(cursor.getColumnIndex("remark"));

                Log.d(TAG, "useDB: "+_id+" "+hour);
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,hour);
                calendar.set(Calendar.MINUTE,minute);
                Boolean selected;
                if(selected_int == 1)selected = true;
                else selected = false;
                ClockBean bean = new ClockBean(_id,calendar,remark,selected);
                DATA.add(bean);
            }
            Collections.sort(DATA,comparator);
            adapter.notifyDataSetChanged();
        }
        else {
            Log.d(TAG, "useDB: 打开数据库失败");
        }

        db.close();
    }

    /**
     * 新增数据库记录
     */
    public void addClock(Integer hour, Integer minute, Boolean selected, String remark)
    {
        SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(getContext());
        SQLiteDatabase db = helper.getWritableDatabase();
        Integer selected_int;
        if(selected == true)selected_int = 1;
        else selected_int = 0;
        if(db.isOpen()){
            String sql = "insert into clock(hour,minute,selected,remark) values(?,?,?,?)";
            db.execSQL(sql, new Object[]{hour,minute,selected_int,remark});
        }
        else {
            Log.d(TAG, "useDB: 打开数据库失败");
        }

        db.close();
    }

    /**
     * 删除数据库记录
     */
    public void deleteClock(Integer id)
    {
        SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(getContext());
        SQLiteDatabase db = helper.getWritableDatabase();

        if(db.isOpen()){
            String sql = "delete from clock where _id = ?";
            db.execSQL(sql, new Object[]{id});
        }
        else {
            Log.d(TAG, "useDB: 打开数据库失败");
        }

        db.close();
    }

    /**
     * edit数据库记录
     */
    public void editClock(Integer id, Integer hour, Integer minute, Boolean selected, String remark)
    {
        SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(getContext());
        SQLiteDatabase db = helper.getWritableDatabase();
        Integer selected_int;
        if(selected == true)selected_int = 1;
        else selected_int = 0;
        if(db.isOpen()){
            String sql = "update clock set hour=?,minute=?,selected=?,remark=? where _id=?";
            db.execSQL(sql, new Object[]{hour,minute,selected_int,remark,id});
        }
        else {
            Log.d(TAG, "useDB: 打开数据库失败");
        }

        db.close();
    }

    /**
     * 更改数据库里的选择项
     */
    public void ifCheckedSetDatabase(Integer position, boolean selected)
    {
        Integer id = DATA.get(position).getId();
        SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(getContext());
        SQLiteDatabase db = helper.getWritableDatabase();
        Integer selected_int;
        if(selected == true)selected_int = 1;
        else selected_int = 0;
        if(db.isOpen()){
            String sql = "update clock set selected=? where _id=?";
            db.execSQL(sql, new Object[]{selected_int,id});
        }
        else {
            Log.d(TAG, "useDB: 打开数据库失败");
        }

        db.close();
    }

//    /**
//     * 初始化闹钟列表
//     */
//    private void initialize_data() {
//        for (int i = 0; i < 10; i++)
//        {
//            Calendar date = Calendar.getInstance();
//            date.set(Calendar.HOUR_OF_DAY,10);
//            date.set(Calendar.MINUTE,i*3+1);
//            ClockBean b = new ClockBean(i,date,"",false);
////            Log.d(TAG, "initialize_data: "+now.toString());
//            DATA.add(b);
//        }
//    }

    /**
     * 自定义广播接收器
     */
    class TimeChangeReceiver extends BroadcastReceiver {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Intent.ACTION_TIME_TICK:
                    //每过一分钟 触发
                    Log.d(TAG, "onTimeChanged: "+"一分钟过去了");
                    Log.d(TAG, String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY))+":"+String.valueOf(Calendar.getInstance().get(Calendar.MINUTE)));
                    judgeAlarm();
                    break;
                case Intent.ACTION_TIME_CHANGED:
                    //设置了系统时间
                    Toast.makeText(context, "system time changed", Toast.LENGTH_SHORT).show();
                    break;
                case Intent.ACTION_TIMEZONE_CHANGED:
                    //设置了系统时区的action
                    Toast.makeText(context, "system time zone changed", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }


    /**
     * 在广播接收器里调用，每一分钟检查有无触发的闹钟
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void judgeAlarm() {
        Calendar now = Calendar.getInstance();
        Integer minute = now.get(Calendar.MINUTE);
        Integer hour = now.get(Calendar.HOUR_OF_DAY);
        for(int i = 0; i < DATA.size(); i++)
        {
            Calendar calendar = DATA.get(i).getTime();
            if(calendar.get(Calendar.HOUR_OF_DAY)==hour && calendar.get(Calendar.MINUTE)==minute && DATA.get(i).getSelected())
            {
                Log.d(TAG, "闹钟"+DATA.get(i).getId()+"开始响铃");
                play();
            }
        }
    }

    /**
     * 音乐播放 和震动功能
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void play(){
        Vibrator vibrator = (Vibrator)getContext().getSystemService(getContext().VIBRATOR_SERVICE);
        long[] patter = {500, 1000};
        vibrator.vibrate(patter, 0);
        myPlayer = new MyPlayer();
        myPlayer.play(getActivity().getApplicationContext(), Uri.parse("android.resource://" + getContext().getPackageName() + "/" + music));
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        String content = "闹钟正在响铃\n";
        builder.setMessage(content);
        LinearLayout alarm = (LinearLayout)getLayoutInflater().inflate(R.layout.alarm_dialog,null);
        builder.setIcon(R.drawable.ic_notifications_black_24dp).setView(alarm);
        builder.setPositiveButton("关闭闹铃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("对话框测试","点击了确定");
                myPlayer.pause();
                vibrator.cancel();
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                myPlayer.pause();
                vibrator.cancel();
            }
        });
        dialog.show();

        makeNotification();
    }

    private String createNotificationChannel(String channelID, String channelNAME, int level) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationManager manager = (NotificationManager) getActivity().getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(channelID, channelNAME, level);
            manager.createNotificationChannel(channel);
            return channelID;
        } else {
            return null;
        }
    }


    private void makeNotification() {
        Intent intent = new Intent(getActivity(), MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, 0);

        String channelId = createNotificationChannel("my_channel_ID", "my_channel_NAME", NotificationManager.IMPORTANCE_HIGH);
        NotificationCompat.Builder notification = new NotificationCompat.Builder(getContext(), channelId)
                .setContentTitle("闹钟响铃")
                .setContentText("您有一个闹钟正在响铃，点击跳转到应用进行操作")
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.ic_baseline_alarm_on_24)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getContext());
        notificationManager.notify(100, notification.build());

//        NotificationManager notificationManager = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
//            NotificationChannel channel = new NotificationChannel("alarm", "测试", NotificationManager.IMPORTANCE_HIGH);
//            notificationManager.createNotificationChannel(channel);
//        }
//        Notification notification = new NotificationCompat.Builder(getActivity().getApplicationContext(),"alarm").setContentTitle("this is a notification")//标题
//                .setContentText("this is a content:")//内容
//                .setSmallIcon(R.drawable.ic_baseline_alarm_on_24).build();

//        //获取系统提供的通知管理服务
//        manager = (NotificationManager) getActivity().getSystemService(NOTIFICATION_SERVICE);
//        //判断是否为8.0以上系统，是的话新建一个通道
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
////创建一个通道 一参：id  二参：name 三参：统通知的优先级
//            @SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel("chId", "聊天信息", NotificationManager.IMPORTANCE_MAX);
//            manager.createNotificationChannel(channel);//创建
//            channel.setVibrationPattern(new long[]{0});//通道来控制震动
//            tong();
//        }else {
//            tong();
//        }
    }
//    private void tong() {
//        manager = (NotificationManager) getActivity().getSystemService(NOTIFICATION_SERVICE);//获取管理类的实例
//        Intent intent=new Intent(getContext(),MainActivity.class);
//        //PendingIntent点击通知后跳转，一参：context 二参：一般为0 三参：intent对象 四参：一般为0
//        PendingIntent pendingIntent=PendingIntent.getActivity(getContext(),0,intent,0);
//        Notification builder = new NotificationCompat.Builder(getContext(), "chId")
//                .setContentTitle("this is a notification")//标题
//                .setContentText("this is a content:lalalallalaal")//内容
//                .setSmallIcon(R.drawable.ic_baseline_alarm_on_24)//图片
//                .setContentIntent(pendingIntent)//点击通知跳转
//                .setAutoCancel(true)//完成跳转自动取消通知
//                .build();
//        manager.notify(1, builder);//让通知显示出来
//    }


    /**
     * 接收活动返回结果
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) { //resultCode为回传的标记,回传的是RESULT_OK
          case RESULT_OK:
//        switch (requestCode) { //requestCode
//            case 1:

                Bundle b=data.getExtras(); //data为B中回传的Intent
                String type=b.getString("type");
                String hour_str=b.getString("hour_return");
                String minute_str=b.getString("minute_return");
                String remark=b.getString("remark_return");

                Log.d(TAG, "onActivityResult: "+hour_str+":"+minute_str);

                Integer hour = Integer.parseInt(hour_str);
                Integer minute = Integer.parseInt(minute_str);
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,hour);
                calendar.set(Calendar.MINUTE,minute);

                ClockBean bean = new ClockBean();
                //未设置id
//                bean.setId();
                bean.setTime(calendar);
                bean.setRemark(remark);
                bean.setSelected(true); //新建闹钟默认开启
                if(type.equals("new"))
                {
//                    DATA.add(bean);
                    addClock(hour,minute,true,remark);//新建闹钟默认开启
                    Toast.makeText(getContext(),"新建闹钟成功",Toast.LENGTH_SHORT).show();
                    refresh();
                }
                else if(type.equals("edit"))
                {
//                    DATA.get(editPosition).setTime(calendar);
//                    DATA.get(editPosition).setRemark(remark);
                    Integer id = DATA.get(editPosition).getId();
                    Boolean selected = DATA.get(editPosition).getSelected();
                    editClock(id,hour,minute,selected,remark);
                    Toast.makeText(getContext(),"编辑闹钟成功",Toast.LENGTH_SHORT).show();
                    refresh();
                }
                Collections.sort(DATA,comparator);
                adapter.notifyDataSetChanged();//适配器刷新列表

                break;
            default:
                break;
        }
    }

    /////////////////////////////////////////////////////////////

//    /**
//     * 菜单创建
//     */
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//        return true;
//    }
//
//    /**
//     * 菜单选项
//     */
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }
//
//        return super.onOptionsItemSelected(item);
//    }


}